package com.corecloud.controller.sys;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.corecloud.entity.SysAppEntity;
import com.corecloud.service.SysAppService;
import com.corecloud.tools.AjaxResultData;
import com.corecloud.tools.MD5Utils;
import com.corecloud.tools.PageDemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.security.Principal;
import java.util.Date;

/**
 * 第三方接入管理
 *
 */
@Controller
@RequestMapping("/app")
public class AppController {


	@Autowired
	private SysAppService sysAppService;


	/**
	 * 接入管理首页
	 * @param principal
	 * @return
	 */
	@RequestMapping("/index")
	public ModelAndView index(Principal principal){
		ModelAndView modelAndView = new ModelAndView("app/index");
		return modelAndView;
	}



	/**
	 * 角色列表页数据（分页）
	 * @param principal 登录用户信息
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public Page<SysAppEntity> list(Principal principal, SysAppEntity info, PageDemo pageDemo){
		QueryWrapper<SysAppEntity> qw = new QueryWrapper();
		//拼装查询条件
		if(!StringUtils.isEmpty(info.getIsValid())){
			qw.eq("is_valid",info.getIsValid());
		}
		if(!StringUtils.isEmpty(info.getName())){
			qw.like("name",info.getName());
		}
		OrderItem oi = new OrderItem();
		oi.setAsc(false);
		oi.setColumn("id");
		pageDemo.addOrder(oi);
		return sysAppService.getInfoByPage(pageDemo,qw);
	}


	/**
	 * 接入管理首页
	 * @param principal
	 * @return
	 */
	@RequestMapping("/add")
	public ModelAndView add(Principal principal){
		ModelAndView modelAndView = new ModelAndView("app/add");
		return modelAndView;
	}


	/**
	 * 保存第三方系统接入信息
	 * @param principal
	 * @param info
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public AjaxResultData save(Principal principal,SysAppEntity info){
		if(StringUtils.isEmpty(info.getName())){
			return new AjaxResultData(500,"请填写系统名称");
		}
		if(StringUtils.isEmpty(info.getAppUrl())){
			return new AjaxResultData(500,"请填写URL地址");
		}
		if(StringUtils.isEmpty(info.getRedirectUriMul())){
			return new AjaxResultData(500,"请填写URL回调地址");
		}

		//利用MD5加密,将当前时间转换为字符串并加密为32位(小)格式设置为clientId,secret则需要二次加密
		info.setClientId(MD5Utils.encodeByMD5(new Date().getTime()+"",""));
		String secret = MD5Utils.encodeByMD5(new Date().getTime()+"","APP");
		info.setClientClearSecret(secret);
		info.setClientSecret(new BCryptPasswordEncoder().encode(secret));
		//设置默认参数
		info.setAccessTokenValiditySeconds(86400);
		info.setRefreshTokenValiditySeconds(86400);
		info.setGrantTypeMul("authorization_code,client_credentials");
		try {
			SysAppEntity otherApp = sysAppService.selectOne(new QueryWrapper<SysAppEntity>().eq("name",info.getName()));
			if(otherApp != null){
				return new AjaxResultData(500,"该名称已被占用");
			}
			sysAppService.insertInfo(info);
			return new AjaxResultData("操作成功");
		}catch (Exception e){
			return new AjaxResultData(500,"操作失败,请联系管理员");
		}
	}



	/**
	 * 接入修改页
	 * @param principal
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit(Principal principal,Integer id){
		ModelAndView modelAndView = new ModelAndView("app/edit");
		if(id != null){
			modelAndView.addObject("appInfo",sysAppService.selectOne(new QueryWrapper<SysAppEntity>().eq("id",id)));
		}
		return modelAndView;
	}


	/**
	 * 保存第三方系统接入修改信息
	 * @param principal
	 * @param info
	 * @return
	 */
	@RequestMapping("/update")
	@ResponseBody
	public AjaxResultData update(Principal principal,SysAppEntity info){
		if(StringUtils.isEmpty(info.getAppUrl())){
			return new AjaxResultData(500,"请填写URL地址");
		}
		if(StringUtils.isEmpty(info.getRedirectUriMul())){
			return new AjaxResultData(500,"请填写URL回调地址");
		}
		try {
			SysAppEntity oldApp = sysAppService.selectOne(new QueryWrapper<SysAppEntity>().eq("id",info.getId()));
			if(oldApp == null){
				return new AjaxResultData(500,"参数异常,未查到对应数据");
			}
			oldApp.setAppUrl(info.getAppUrl());
			oldApp.setRedirectUriMul(info.getRedirectUriMul());
			oldApp.setIsValid(info.getIsValid());
			sysAppService.updateInfo(oldApp);
			return new AjaxResultData("操作成功");
		}catch (Exception e){
			return new AjaxResultData(500,"操作失败,请联系管理员");
		}
	}




	/**
	 * 删除第三方系统接入信息
	 * @param principal
	 * @param appId
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public AjaxResultData delete(Principal principal,Integer appId){
		if(appId == null){
			return new AjaxResultData(500,"请填写URL地址");
		}
		try {
			SysAppEntity deleteInfo = sysAppService.selectOne(new QueryWrapper<SysAppEntity>().eq("id",appId));
			if(deleteInfo == null){
				return new AjaxResultData(500,"参数异常,未查到对应数据");
			}
			sysAppService.deleteInfo(deleteInfo.getId());
			return new AjaxResultData("操作成功");
		}catch (Exception e){
			return new AjaxResultData(500,"操作失败,请联系管理员");
		}
	}





}
